using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using SmartHealthcare.Read.Api.Application.Command.HospitalExpense;
using SmartHealthcare.Read.Api.DTo;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SmartHealthcare.Read.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HospitalExpenseController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<HospitalExpenseController> _logger;

        public HospitalExpenseController(IMediator mediator, ILogger<HospitalExpenseController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取住院费用记录列表
        /// </summary>
        /// <param name="medicalCard">病人卡号</param>
        /// <param name="patientName">患者姓名</param>
        /// <param name="inpatientRegistryId">住院登记ID</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="itemType">费用类型</param>
        /// <returns>住院费用记录列表</returns>
        [HttpGet]
        public async Task<APIResult<List<HospitalExpenseDto>>> GetHospitalExpenses(
            [FromQuery] string medicalCard = null,
            [FromQuery] string patientName = null,
            [FromQuery] long? inpatientRegistryId = null,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] string itemType = null)
        {
            _logger.LogInformation($"接收到获取住院费用记录请求，病人卡号：{medicalCard}，患者姓名：{patientName}，住院登记ID：{inpatientRegistryId}");

            var command = new GetHospitalExpensesCommand
            {
                MedicalCard = medicalCard,
                PatientName = patientName,
                InpatientRegistryId = inpatientRegistryId,
                StartTime = startTime,
                EndTime = endTime,
                ItemType = itemType
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取住院费用统计
        /// </summary>
        /// <param name="medicalCard">病人卡号</param>
        /// <param name="inpatientRegistryId">住院登记ID</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="groupByDay">是否按天统计</param>
        /// <param name="groupByType">是否按类型统计</param>
        /// <returns>住院费用统计信息</returns>
        [HttpGet]
        public async Task<APIResult<ExpenseStatisticsDto>> GetExpenseStatistics(
            [FromQuery] string medicalCard = null,
            [FromQuery] long? inpatientRegistryId = null,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] bool groupByDay = true,
            [FromQuery] bool groupByType = true)
        {
            _logger.LogInformation($"接收到获取住院费用统计请求，病人卡号：{medicalCard}，住院登记ID：{inpatientRegistryId}");

            var command = new GetExpenseStatisticsCommand
            {
                MedicalCard = medicalCard,
                InpatientRegistryId = inpatientRegistryId,
                StartTime = startTime,
                EndTime = endTime,
                GroupByDay = groupByDay,
                GroupByType = groupByType
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 生成每日费用清单
        /// </summary>
        /// <param name="medicalCard">病人卡号</param>
        /// <param name="inpatientRegistryId">住院登记ID</param>
        /// <param name="reportDate">报表日期</param>
        /// <param name="reportFormat">报表格式（PDF/Excel）</param>
        /// <returns>报表文件</returns>
        [HttpGet]
        public async Task<IActionResult> GenerateDailyExpenseReport(
            [FromQuery] string medicalCard = null,
            [FromQuery] long? inpatientRegistryId = null,
            [FromQuery] DateTime? reportDate = null,
            [FromQuery] string reportFormat = "PDF")
        {
            _logger.LogInformation($"接收到生成每日费用清单请求，病人卡号：{medicalCard}，住院登记ID：{inpatientRegistryId}，报表日期：{reportDate}");

            var command = new GenerateDailyExpenseReportCommand
            {
                MedicalCard = medicalCard,
                InpatientRegistryId = inpatientRegistryId,
                ReportDate = reportDate,
                ReportFormat = reportFormat
            };

            var result = await _mediator.Send(command);

            if (result.Code != APIEnums.Success)
            {
                return BadRequest(result);
            }

            // 设置文件名
            var fileName = $"每日费用清单_{(reportDate ?? DateTime.Now):yyyyMMdd}.pdf";
            if (reportFormat.ToUpper() == "EXCEL")
            {
                fileName = $"每日费用清单_{(reportDate ?? DateTime.Now):yyyyMMdd}.xlsx";
                return File(result.Data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            else
            {
                return File(result.Data, "application/pdf", fileName);
            }
        }
    }
} 